import {getUserInfo, login} from '@/api/sys'
import { setItem,getItem ,removeAllItem} from '@/utils/storage'
import { TOKEN,UserInfo } from '@/constant'
import router,{ resetRouter }from '@/router'
import {setTimeStamp} from '@/utils/auth'
export default {
  namespaced:true,
  state:()=>({
    // 获取token
    token:getItem(TOKEN) || '',
    // 获取用户信息
    userInfo:getItem(UserInfo) || {}
  }),
  mutations:{
    // 获取token
    setToken(state,token){
      state.token = token
      setItem(TOKEN,token)
    },
    // 创建用户信息
    setUserInfo(state,userInfo){
      state.userInfo = userInfo
      setItem(UserInfo, userInfo)
    }
  },
  actions:{
    /**
     * 登录时的动作
     */
    async login(context,userInfo){
      const {username,password} = userInfo
      // const api = await login({
      //   username,
      //   password:md5(password)})
      return new Promise((resolve,reject)=>{
        login({
            name:username,
            password
          }).then((data)=>{
            // 将指传给mutations中的setToken
            this.commit('user/setToken',data.token)
            // 页面跳转
            router.push('/')
            // 保存登陆时间
            setTimeStamp()
            resolve()
          }).catch((err)=>{
            reject(err)
          })
      })
    },
    /**
     * 获取用户信息时的动作
     */
    async getUserInfo(context){
      const res = await getUserInfo()
      this.commit('user/setUserInfo',res)
      return res
    },
    /**
     * 退出登录
     */
    logout(){
      resetRouter()
      this.commit('user/setToken','')
      this.commit('user/setUserInfo',{})
      removeAllItem()
      router.push('/login')
    }
  }
}